#version 330

uniform mat3x3 u_viewInvTrans;
uniform mat4x4 u_View;

uniform int u_numLights;
uniform vec3 u_lightColor[8];
uniform vec3 u_lightDirection[8];
uniform vec3 u_lightPosition[8];
uniform float u_halfAngleCos[8];
uniform float u_cutoffFar[8];
uniform float u_fadeFar[8];

#ifdef TX_COLOR
uniform sampler2D u_Texture;
#endif

in vec3 fs_Normal;
in vec3 fs_Position;

#ifdef TX_COLOR
in vec2 fs_txCoord;
#else
in vec3 fs_Color;
#endif

out vec3 out_Color;

vec3 lightCalc(in vec3 pos, in vec3 dir, in vec3 color, in float halfAngleCos, 
		in float cutoffFar, in float fadeFar) {
	
	// Change position to view space
	vec3 lpos = (u_View * vec4(pos, 1.0f)).xyz;	
	
	// Change direction to view space
	vec3 ldir = normalize(u_viewInvTrans*dir);
	vec3 l2sDir = normalize(fs_Position - lpos);
	
	float dirDirDot = dot(l2sDir, ldir);

	// Compare direction from point to light with direction of light
	if(dirDirDot > halfAngleCos) {
	
		float dist = dirDirDot*distance(lpos, fs_Position);
	
		if(dist < cutoffFar) {	
			float attenuate = 1.0f;
			
			
			if(dist > fadeFar) {
				attenuate -= (dist - fadeFar)/(cutoffFar - fadeFar);
			}
			

			return color*(max(dot(-(l2sDir), normalize(fs_Normal)), 0))*attenuate*pow((dirDirDot-halfAngleCos)/(1 - halfAngleCos),2.0f);			
			
		}
		
	}
	
	return vec3(.0f, .0f, .0f);
}

void main(void)
{
/*
	if(!gl_FrontFacing) {
		discard;
		return;
	}
*/
	float blendWeight = .6f;
	vec3 lightSum = vec3(.0f,.0f,.0f);
	
	for(int i = 0; i < u_numLights; ++i)
		lightSum += blendWeight*lightCalc(u_lightPosition[i], u_lightDirection[i], u_lightColor[i], u_halfAngleCos[i],
			u_cutoffFar[i], u_fadeFar[i]);
	
#ifdef TX_COLOR
	out_Color = (texture(u_Texture, fs_txCoord).rgb * .8f)*lightSum;
#else
	out_Color = (fs_Color*.8f)*lightSum;
	//out_Color = (fs_Color*.8f)*max(0.0f, dot(fs_Normal, -normalize(fs_Position)));
	//out_Color = vec3(0.0f, .5f, 0.0f);
#endif
	
    //out_Color = vec3(max(0.0f,dot(-normalize(fs_Position.xyz),fs_Normal))*.5f + .5f);
    //out_Color = vec3(1.0f, 0.0f, 0.0f);
}